package connectDB;

import java.sql.*;

public class ConnectDB {

    private static Connection conn = null;

    public static Connection getConnection() {
        return conn;
    }

    public ConnectDB() {
        openConnection();
    }

    public void openConnection() {
        if (conn == null) {
            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                String url = "jdbc:sqlserver://Localhost:1433;database=FUJINETTEST";
                conn = DriverManager.getConnection(url, "sa", "123456");
                System.out.println(conn);
            } catch (Exception e) {
                System.out.println("Cannot connect! Please try again!");
            }
        }
    }

    public void closeConnection() {
        if (conn != null) {
            try {
                conn.close();
                conn = null;
                System.out.println("Close connection!");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    public ResultSet excuteQuery(String str) throws SQLException {
        if (conn != null) {
            Statement stt = conn.createStatement();
            return stt.executeQuery(str);
        }
        return null;
    }
    
     public int executeUpdate(String sql) {
        try {
            if (conn != null) {
                PreparedStatement pst = conn.prepareStatement(sql);
                return pst.executeUpdate();
            }

        } catch (Exception e) {
            return -1;
        }
        return -1;
    }
}
